<template>
  <!-- 表格容器 -->
  <div class="table-container">
    <!-- 头部区域 -->
    <div class="header">
      <!-- 搜索表单 -->
      <el-form inline label-width="100px" class="search-form">
        <el-form-item label="项目">
          <el-input size="medium" v-model="searchQuery.project" placeholder="项目" clearable></el-input>
        </el-form-item>
        <el-form-item label="类型">
<!--          <el-input size="medium" v-model="searchQuery.type" placeholder="类型" clearable></el-input>-->
          <el-select v-model="searchQuery.type" clearable placeholder="请选择类型">
            <el-option
                v-for="item in transactionTypes"
                :key="item.code"
                :label="item.name"
                :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间">
          <el-date-picker size="medium" v-model="searchQuery.time" type="date" placeholder="选择日期" clearable></el-date-picker>
        </el-form-item>
        <el-form-item label="金额">
          <el-input size="medium" v-model="searchQuery.amount" placeholder="金额" clearable></el-input>
        </el-form-item>
        <el-form-item label="人员">
<!--          <el-input size="medium" v-model="searchQuery.userName" placeholder="人员" clearable></el-input>-->
          <el-select v-model="searchQuery.userName" clearable placeholder="请选择类型">
            <el-option
                v-for="item in userInfoTypes"
                :key="item.code"
                :label="item.name"
                :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input size="medium" v-model="searchQuery.remark" placeholder="备注" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <div class="button-container">
            <!-- 搜索按钮 -->
            <el-button type="primary" size="medium" @click="getList" :loading="searchLoading" icon="el-icon-search" class="button-spacing">搜索</el-button>
            <el-button type="primary" size="medium" @click="downloadExcel" :loading="searchLoading" icon="el-icon-search" class="button-spacing">下载账目记录</el-button>
            <el-button type="danger" size="medium" icon="el-icon-delete" :loading="searchLoading" @click="handleDelete" class="button-spacing">删除</el-button>
            <file-upload :initial-button-text="buttonText" class="button-spacing" @file-uploaded="refreshData"></file-upload>
          </div>
        </el-form-item>
      </el-form>
      <!-- 按钮区域 -->
      <div class="buttons">
        <el-button type="primary" size="medium" :loading="billLoading" @click="handleButtonBill" icon="el-icon-download" class="button-spacing">生成账单</el-button>
        <el-button type="success" size="medium" @click="handleButton2" icon="el-icon-position" class="button-spacing">发送邮箱</el-button>
      </div>
    </div>
    <!-- 内容区域 -->
    <div class="content">
      <!-- 左侧面板 -->
      <div class="left-panel" @click="detailedBooks">
        <h3>基础明细</h3>
        <!-- 这里可以放置其他逻辑 -->
        <div>
          <span style="color: red">{{ getTypeName(detailedData.maxAmountExpenseName, 'name') }}</span>
          <p>{{ detailedData.maxAmountExpense }}</p>
        </div>
        <div>
          <span style="color: red">{{ getTypeName(detailedData.maxAmountForCurrentYearName, 'name') }}</span>
          <p>{{ detailedData.maxAmountForCurrentYear }}</p>
        </div>
        <div>
          <span style="color: red">{{ getTypeName(detailedData.maxAmountHistoricalName, 'name') }}</span>
          <p>{{ detailedData.maxAmountHistorical }}</p>
        </div>
        <div>
          <span style="color: red">{{ getTypeName(detailedData.maxAmountIncomeName, 'name') }}</span>
          <p>{{ detailedData.maxAmountIncome }}</p>
        </div>
        <div>
          <p>
            <span> 当月总收入 </span><span style="color: red">{{ detailedData.totalIncomeForCurrentMonth }}</span>
            <span> 当月总支出 </span><span style="color: green">{{ detailedData.totalExpenseForCurrentMonth }}</span>
          </p>
          <p>
            <span> 当月结余： </span>
            <span :style="{ color: detailedData.balanceForCurrentMonth > 0 ? 'red' : 'green' }">
              {{ detailedData.balanceForCurrentMonth }}
            </span>
          </p>
        </div>
      </div>
      <!-- 中间面板 -->
      <div class="middle-panel">
        <!-- 表格 -->
      <el-table :data="items" ref="multipleTable" style="width: 100%;" height="524px" @row-dblclick="handleRowDblClick" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column prop="project" label="项目" width="120"></el-table-column>
          <el-table-column prop="type" label="类型" width="120">
            <template slot-scope="scope">
              {{ getTypeName(scope.row.type, 'type') }}
            </template>
          </el-table-column>
          <el-table-column prop="time" label="时间" width="120"></el-table-column>
          <el-table-column prop="amount" label="金额" width="120">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.type === 'expenditure' ? 'green' : 'red' }">
                {{ scope.row.amount }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="userName" label="人员" width="120">
            <template slot-scope="scope">
              {{ getTypeName(scope.row.userName, 'name') }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" :show-overflow-tooltip="showOT" label="备注"></el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalItems"
          style="margin-top: 10px; text-align: center;"
        ></el-pagination>
      </div>
      <!-- 右侧面板 -->
      <div class="right-panel">
        <h3>表单提交</h3>
        <!-- 提交表单 -->
        <el-form label-position="left" label-width="80px" :rules="rules" :model="form" ref="form">
          <el-form-item label="项目" prop="project">
            <el-input v-model="form.project" style="width: 100%;" :disabled="isEditing"></el-input>
          </el-form-item>
          <el-form-item label="类型" prop="type">
<!--            <el-input v-model="form.type" style="width: 100%;" :disabled="isEditing"></el-input>-->
            <el-select v-model="form.type" clearable placeholder="请选择类型" style="width: 100%;" :disabled="isEditing" @change="validateType">
              <el-option
                  v-for="item in transactionTypes"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="金额" prop="amount">
            <el-input v-model="form.amount" style="width: 100%;" @input="validateAmount"></el-input>
          </el-form-item>
          <el-form-item label="人员" prop="userName">
<!--            <el-input v-model="form.userName" style="width: 100%;" :disabled="isEditing"></el-input>-->
            <el-select v-model="form.userName" clearable placeholder="请选择类型" style="width: 100%;" :disabled="isEditing" @change="validateType">
              <el-option
                  v-for="item in userInfoTypes"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间" prop="time">
            <el-date-picker
                v-model="form.time"
                type="date"
                placeholder="选择日期"        style="width: 100%;"
                :picker-options="pickerOptions"
                value-format="yyyy-MM-dd"
                :disabled="isEditing"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" placeholder="备注" style="width: 100%;"></el-input>
          </el-form-item>
          <el-form-item>
            <!-- 新增按钮 -->
            <el-button type="primary" :loading="submitLoading" @click="submitForm" v-if="!isEditing">新增</el-button>
            <!-- 更新按钮 -->
            <el-button type="primary" :loading="submitLoading" @click="updateForm" v-if="isEditing">更新</el-button>
            <!-- 重置按钮 -->
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import fileUpload from "@/views/FileUpload.vue";
export default {
  components:{
    fileUpload
  },
  data() {
    return {
      buttonText: '导入',
      // 列表太长的部分使用...来代表
      showOT: true,
      // 搜索按钮的loading
      searchLoading: false,
      // 生成账单按钮的loading
      billLoading: false,
      // 提交表单的loading
      submitLoading: false,
      // 搜索查询对象
      searchQuery: {
        project: '',
        type: '',
        amount: '',
        userName: '',
        time: '',
        remark: ''
      },
      // 表格数据
      items: [],
      rules: {
        project: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请输入类型', trigger: 'change' }
        ],
        amount: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效的金额（最多两位小数）', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入人员', trigger: 'blur' }
        ],
        time: [
          { required: true, message: '请选择时间', trigger: 'change' }
        ]
      },
      // 当前页码
      currentPage: 1,
      // 每页大小
      pageSize: 10,
      totalItems: 1,
      // 表单数据对象
      form: {
        id: '',
        project: '',
        type: '',
        amount: '',
        userName: '',
        time: '',
        remark: ''
      },
      // 限制时间的选择大于今天
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      detailedData: {},
      // 是否处于编辑状态
      isEditing: false,
      transactionTypes: [], // 存储交易类型的数组
      userInfoTypes: [], // 用户类型的数组
      selectedItems: []
    };
  },
  computed: {
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.detailedBooks()
      this.getList()
      this.fetchTransactionTypes()
    },
    // 获取下拉列表
    fetchTransactionTypes() {
      this.$http.get('api/dictionary/dictionaries', {
        headers: {
          token: localStorage.getItem("token")
        },
        params: {
          parentCode: 'transaction_type'
        }
      }).then(res => {
        if (res.status === 200) {
          this.transactionTypes = res.data
        } else {
          this.$message.error('失败');
        }
      });
      this.$http.get('api/dictionary/dictionaries', {
        headers: {
          token: localStorage.getItem("token")
        },
        params: {
          parentCode: 'user_info'
        }
      }).then(res => {
        if (res.status === 200) {
          this.userInfoTypes = res.data
        } else {
          this.$message.error('失败');
        }
      })
    },
    getTypeName(code, obj) {
      if (obj === 'type') {
        const type = this.transactionTypes.find(item => item.code === code);
        return type ? type.name : code;
      } else if (obj === 'name') {
        const type = this.userInfoTypes.find(item => item.code === code);
        return type ? type.name : code;
      } else {
        return code
      }
    },
    getTypeCode(name, obj) {
      if (obj === 'type') {
        const type = this.transactionTypes.find(item => item.name === name);
        return type ? type.code : name;
      } else if (obj === 'name') {
        const type = this.userInfoTypes.find(item => item.name === name);
        return type ? type.code : name;
      } else {
        return name
      }
    },
    detailedBooks() {
      this.$http.get('bookKeeping/detailedBooks', {
        headers: {
          token: localStorage.getItem("token")
        }
      }).then(res => {
        this.detailedData = res.data.data.success
      })
    },
    async getList() {
      this.searchLoading = true;
      const { project, type, time, amount, userName, remark } = this.searchQuery;
      const params = {
        project: project || '',
        type: type || '',
        time: time || '',
        amount: amount || '',
        userName: userName || '',
        remark: remark || '',
        currentPage: this.currentPage,
        pageSize: this.pageSize
      };
      try {
        const res = await this.$http.get('bookKeeping/getList', {
          headers: {
            token: localStorage.getItem("token")
          },
          params: params
        });
        if (res.status === 200) {
          this.items = res.data.records;
          this.totalItems = res.data.total;
        }
      } catch (error) {
        console.error('Error fetching list data:', error);
      } finally {
        this.searchLoading = false;
      }
    },
    downloadExcel() {
      this.searchLoading = true
      this.$http.get('bookKeeping/download', {
        headers: {
          token: localStorage.getItem("token")
        },
        responseType: 'blob'
      }).then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', new Date().getTime() + '_账目记录.xlsx'); // 设置下载的文件名
        document.body.appendChild(link);
        link.click();
      }).finally(() => {
        this.searchLoading = false
      });
    },

    handleSelectionChange(val) {
      this.selectedItems = val;
    },
    handleDelete() {
      if (this.selectedItems.length === 0) {
        this.$message({
          type: 'warning',
          message: '请至少选择一条数据'
        });
        return;
      }

      const selectedIds = this.selectedItems.map(item => item.id);

      this.$confirm('此操作将永久删除选中的记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post('bookKeeping/delete', selectedIds, {
          headers: {
            token: localStorage.getItem("token")
          }
        }).then(res => {
          if (res.status === 200) {
            this.$message.success(res.data);
            this.getList(); // 刷新列表
          } else {
            this.$message.error(res.data);
          }
        }).finally(() => {
          this.submitLoading = false;
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 处理每页大小变化
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.getList()
    },
    // 处理当前页码变化
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.getList()
    },
    validateType() {
      this.$refs.form.validateField('type');
    },
    validateName() {
      this.$refs.form.validateField('userName');
    },
    validateAmount() {
      this.$refs.form.validateField('amount', (errorMessage) => {
        if (errorMessage) {
          this.$message.error(errorMessage);
        }
      });
    },
    // 提交表单
    submitForm() {

      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          // 将金额字段转换为 double 类型
          this.form.amount = parseFloat(this.form.amount);

          // 检查金额是否为有效数字
          if (isNaN(this.form.amount)) {
            this.$message.error('请输入有效的金额');
            this.submitLoading = false;
            return;
          }
          this.$http.post('bookKeeping/add', this.form, {
            headers: {
              token: localStorage.getItem("token")
            }
          }).then(res => {
            if (res.status === 200) {
              this.$message.success('新增成功');
              this.resetForm() // 重置表单
              this.getList(); // 刷新列表
            } else {
              this.$message.error('新增失败');
            }
          }).finally(() => {
            this.submitLoading = false;
          });
        } else {
          return false;
        }
      });
    },
    // 更新表单
    updateForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          // 将金额字段转换为 double 类型
          this.form.amount = parseFloat(this.form.amount);

          // 检查金额是否为有效数字
          if (isNaN(this.form.amount)) {
            this.$message.error('请输入有效的金额');
            this.submitLoading = false;
            return;
          }

          this.$http.post(`bookKeeping/updateBook`, this.form, {
            headers: {
              token: localStorage.getItem("token")
            }
          }).then(res => {
            if (res.status === 200) {
              this.$message.success('更新成功');
              this.resetForm(); // 重置表单
              this.getList(); // 刷新列表
            } else {
              this.$message.error('更新失败');
            }
          }).finally(() => {
            this.submitLoading = false;
          });
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm() {
      // 重置表单的所有字段和验证状态
      this.$refs.form.resetFields();

      // 重置表单数据
      this.form = {
        project: '',
        type: '',
        amount: '',
        userName: '',
        time: '',
        remark: ''
      };

      // 重新绑定事件监听器
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });

      // 重置编辑状态
      this.isEditing = false;
    },
    // 格式化日期
    formatDate(date) {
      if (date) {
        const d = new Date(date);
        return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
      }
      return '';
    },
    // 按钮1的处理逻辑
    handleButtonBill() {
      const currentDate = this.formatDateYM(new Date(), 'yyyy-MM');

      const promptUser = (previousValue = '', showError = false) => {
        this.$prompt(`请输入用户名和年月，格式为（用户名, yyyy-MM）。如果不填写年月，默认为当前年月（${currentDate}）`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: previousValue, // 传递之前的输入值
          inputPattern: showError ? /^(\S+)([，,]\s*\d{4}-\d{2})?$/ : null, // 只在需要时进行校验
          inputErrorMessage: '输入格式不正确，应为（用户名, yyyy-MM）'
        }).then(({ value }) => {
          // 使用正则表达式分割输入值
          const parts = value.split(/[,，]/, 2); // 最多分割两次，支持中文和英文逗号
          const userName = parts[0].trim(); // 取第一个部分作为用户名
          const yearMonth = parts.length > 1 ? parts[1].trim() : ''; // 取第二个部分作为年月

          // 验证年月格式是否正确
          const yearMonthPattern = /^\d{4}-\d{2}$/;
          if (yearMonth && !yearMonthPattern.test(yearMonth)) {
            this.$message({
              type: 'error',
              message: '年月格式不正确，应为（yyyy-MM）',
              customClass: 'custom-message' // 添加自定义类
            });
            promptUser(value, true); // 重新显示 $prompt 并传递当前输入值，同时显示错误信息
            return;
          }

          const finalYearMonth = yearMonth || currentDate;

          this.billLoading = true;
          this.$http.get('bookKeeping/currentMonthSummary', {
            headers: {
              token: localStorage.getItem("token")
            },
            params: {
              userName: this.getTypeCode(userName, 'name'),
              yearMonth: finalYearMonth
            }
          }).then(res => {
            if (res.status === 200) {
              const bill = {
                id: 'TEMP-' + finalYearMonth + '-' + new Date().getTime(),
                customerName: userName, // 用户名称
                amount: res.data.balanceAmount, // 当月收支明细金额
                date: this.formatDate(new Date()), // 当前时间
                balanceType: res.data.balanceType, // "收入大于支出" : "支出大于收入"
                totalExpense: res.data.totalExpense, // 当月总支出
                totalIncome: res.data.totalIncome, // 当月总收入
                projectBalances: res.data.projectBalances, // 所有项目收支明细
              };
              // 导航到预览页面并传递账单数据
              this.$router.push({ name: 'BillPreview', params: { bill } });
            }
          }).finally(() => {
            this.billLoading = false;
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消输入',
            customClass: 'custom-message' // 添加自定义类
          });
        });
      };

      promptUser(); // 初始调用
    }
    ,
    formatDateYM(date, format = 'yyyy-MM-dd') {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      if (format === 'yyyy-MM') {
        return `${year}-${month}`;
      }
      return `${year}-${month}-${day}`;
    },
    refreshData() {
      // 刷新数据的方法
      this.getList(); // 调用获取列表数据的方法
    },
    // 按钮2的处理逻辑
    handleButton2() {
      console.log('Button 2 clicked');
    },
    // 按钮3的处理逻辑
    handleButton3() {
      console.log('Button 3 clicked');
    },
    // 双击表格行处理
    handleRowDblClick(row) {
      this.isEditing = true;
      this.form = {
        ...row,
        amount: row.amount.toString(), // 确保金额字段是字符串
        time: this.formatDate(row.time) // 格式化日期
      };
    }
  },
  mounted() {
    // 动态添加样式
    const style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = `    .custom-message {
      z-index: 9999 !important; /* 确保提示信息始终位于最上层 */
    }
  `;
    document.head.appendChild(style);
  }
};
</script>

<style scoped>
/* 样式代码 */
.button-spacing {
  margin-right: 10px; /* 添加间距 */
}

/* 确保所有按钮在同一行内 */
.button-container {
  display: flex;
  align-items: center;
  flex-wrap: nowrap; /* 防止换行 */
}

/* 确保每个按钮有足够的空间 */
.button-container .el-button,
.button-container .custom-file-upload {
  margin-left: 10px; /* 调整按钮之间的间距 */
}
.table-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  gap: 10px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

.button-spacing {
  margin-right: 10px;
}

.content {
  display: flex;
  flex: 1;
  gap: 10px;
}

.left-panel {
  flex: 1;
  min-width: 200px;
  padding: 10px;
  box-sizing: border-box;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.middle-panel {
  flex: 3;
  min-width: 400px;
  padding: 10px;
  box-sizing: border-box;
  overflow: auto;
  background-color: #ffffff;
  border-radius: 4px;
}

.right-panel {
  flex: 2;
  min-width: 300px;
  padding: 10px;
  box-sizing: border-box;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.el-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-table {
  width: 100%;
  max-width: 100%;
}

.el-pagination {
  text-align: center;
}

h3 {
  margin-bottom: 10px;
  font-size: 18px;
  color: #333;
}
</style>
